<template>
  <a-card :bordered="false" class="comment-container">
    <inner-post-comment v-if="!loading" :comments="commentList" />
    <a-skeleton v-if="loading" animation>
      <a-space direction="vertical" :style="{ width: '100%' }" size="large">
        <a-skeleton-shape />
        <a-skeleton-line :rows="3" :widths="['40%', '100%', '100%']" />
      </a-space>
    </a-skeleton>
    <template #actions>
      <a-button
        v-if="!commentVisible"
        type="primary"
        shape="round"
        @click="commentVisible = !commentVisible"
      >
        <template #icon>
          <IconMessage />
        </template>
        评论
      </a-button>
    </template>
    <div v-if="commentVisible" class="md-editor-container">
      <a-textarea
        v-model="commentContent"
        placeholder="有好交流哦~"
        style="height: 100px"
      />
      <a-row class="pt-1.5">
        <a-col :flex="1" />
        <a-col :span="5.5">
          <a-space>
            <a-button @click="commentVisible = !commentVisible">取消</a-button>
            <a-button
              type="primary"
              style="text-align: right"
              :loading="submitting"
              @click="submitComment"
            >
              提交
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>
  </a-card>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue';
import { IconMessage } from '@arco-design/web-vue/es/icon';
import { Message } from '@arco-design/web-vue';
import { OjPostCommentService } from '@/api/gen-api/services/OjPostCommentService.ts';
import InnerPostComment from '@/views/post/info/components/inner-post-comment.vue';
import { useRoute } from 'vue-router';
import { PostCommentVo } from '@/api/gen-api/models/post/PostCommentVo.ts';

// UI状态
const commentVisible = ref(false);
const commentContent = ref('');
const submitting = ref(false);
const loading = ref(false);

// 获取帖子ID
const route = useRoute();
const postIdStr = ref(route.query.postId as string);
const postId = ref(Number(postIdStr.value));

// 评论列表
const commentList = ref<PostCommentVo[]>([]);

// 监听挂载
onMounted(() => {
  console.log('组件挂载，准备获取评论列表');
  console.log('帖子ID:', postIdStr.value, '(转换为数字:', postId.value, ')');
  
  // 延迟获取评论，确保DOM已更新
  nextTick(() => {
    getRootComment();
  });
});

// 提交评论
const submitComment = () => {
  // 前端验证评论内容不能为空
  if (!commentContent.value || commentContent.value.trim() === '') {
    Message.error('评论内容不能为空');
    return;
  }
  
  // 验证帖子ID
  if (!postIdStr.value || isNaN(postId.value) || postId.value <= 0) {
    Message.error('帖子ID无效');
    console.error('无效的帖子ID:', postIdStr.value, '转换值:', postId.value);
    return;
  }
  
  submitting.value = true;
  
  // 记录提交的内容，用于调试
  console.log('准备提交评论:', {
    content: commentContent.value.trim(),
    postId: postId.value
  });
  
  OjPostCommentService.save({
    content: commentContent.value.trim(),
    postId: postId.value
  })
    .then(res => {
      console.log('评论提交响应:', res);
      if (res.code === 200 && res.result) {
        Message.success('评论成功');
        commentVisible.value = false;
        commentContent.value = '';
        // 重新加载评论列表
        getRootComment();
      } else {
        Message.error(res.message || '评论提交失败');
        console.error('评论提交失败:', res);
      }
    })
    .catch(error => {
      console.error('评论提交异常:', error);
      Message.error('评论提交失败，请重试');
    })
    .finally(() => {
      submitting.value = false;
    });
};

/**
 * 获取根节点评论
 */
const getRootComment = () => {
  if (!postIdStr.value || isNaN(postId.value) || postId.value <= 0) {
    console.error('获取评论列表失败: 无效的帖子ID', postIdStr.value);
    return;
  }
  
  loading.value = true;
  console.log('开始获取帖子评论列表, postId:', postIdStr.value);
  
  // 使用原始字符串ID调用API
  OjPostCommentService.list(postIdStr.value)
    .then(res => {
      console.log('获取评论列表响应:', res);
      
      if (res.code === 200 && res.result) {
        commentList.value = res.result;
        console.log('获取评论列表成功, 共', commentList.value.length, '条评论');
        
        // 处理评论数据，添加所需属性
        commentList.value.forEach(comment => {
          // 确保expandedFlag有值
          if (comment.expandedFlag === undefined) {
            comment.expandedFlag = false;
          }
        });
      } else {
        console.warn('获取评论列表失败:', res.message);
        commentList.value = [];
        Message.error(res.message || '获取评论列表失败');
      }
    })
    .catch(error => {
      console.error('获取评论列表异常:', error);
      Message.error('获取评论列表失败，请刷新重试');
      commentList.value = [];
    })
    .finally(() => {
      loading.value = false;
    });
};
</script>

<style scoped lang="less">
.comment-container {
  margin-top: 16px;
  
  .md-editor-container {
    margin-top: 16px;
    border-top: 1px solid var(--color-border-2);
    padding-top: 16px;
  }
  
  :deep(.arco-textarea) {
    resize: none;
    border-radius: 4px;
    
    &:focus {
      border-color: var(--color-primary-6);
    }
  }
  
  .pt-1\.5 {
    padding-top: 12px;
  }
}
</style>
